package com.beg.cant.comment.utils;

import com.alibaba.fastjson.JSONObject;
import com.beg.cant.comment.properties.WeChatProperties;
import org.apache.http.HttpEntity;
//import org.springframework.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.rmi.RemoteException;
import java.util.*;

@Component
public class WechatSecurityHelper {
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
    private static final String CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=";
    private static final String CHECK_IMG_URL = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=";
    private static final RestTemplate restTemplate = new RestTemplate();
    private static String cachedToken = "";
    private static long tokenExpireTime = 0;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 文本安全校验入口
     *
     * @param text 待检测文本
     * @return true-安全 false-风险
     */
    public void checkText(String text, String openid) throws IOException {
        String token = getValidToken();
//        checkContent(token, text, openid);
    }

    // 获取有效access_token（带缓存）
    private String getValidToken() {
        if (System.currentTimeMillis() < tokenExpireTime) {
            return cachedToken;
        }
        Map<String, Object> response = restTemplate.getForObject(
                TOKEN_URL, Map.class, weChatProperties.getAppid(), weChatProperties.getSecret());

        if (response == null || response.containsKey("errcode")) {
            throw new RuntimeException("获取Token失败: " + response);
        }

        cachedToken = (String) response.get("access_token");
        tokenExpireTime = System.currentTimeMillis() +
                ((Integer) response.get("expires_in") - 300) * 1000L; // 提前5分钟过期
        return cachedToken;
    }

    // 执行内容检查
    public void checkContent(String text, String openid) throws IOException {
        String token = getValidToken();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost request = new HttpPost(CHECK_URL + token);
        request.addHeader("Content-Type", "application/json");
        Map<String, Object> map = new HashMap<>();
        map.put("content", text);
//        map.put("scene", 2);
//        map.put("version", 1);
        map.put("openid", openid);

        String body = JSONObject.toJSONString(map);
        System.out.println(body);
        request.setEntity(new StringEntity(body, ContentType.create("text/json", "UTF-8")));
        response = httpclient.execute(request);
        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity, "UTF-8");
        JSONObject jso = JSONObject.parseObject(result);
        Object errcode = jso.get("errcode");
        int errCode = (int) errcode;
        if (errCode!=0) {
            throw new RemoteException("内容不合规");
        }
    }

    // 修正后的 downloadImage 方法
    private File downloadImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);

        try (InputStream inputStream = connection.getInputStream()) {
            File tempFile = File.createTempFile("img_", ".jpg");
            Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            tempFile.deleteOnExit();
            return tempFile;
        }
    }

    // 修正后的 checkImageSecurity 方法
    public void checkImageSecurity(MultipartFile imageUrl) {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            // 1. 创建临时文件并确保自动清理
            File tempFile = File.createTempFile("upload", ".tmp");
            tempFile.deleteOnExit(); // JVM退出时删除临时文件[7](@ref)

            // 2. 将上传的文件内容写入临时文件（假设 imageUrl 是 MultipartFile 类型）
            try (InputStream inputStream = imageUrl.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            // 3. 构建 multipart/form-data 请求体
            ContentType contentType = ContentType.create(imageUrl.getContentType()); // 动态获取文件类型[1,5](@ref)
            FileBody fileBody = new FileBody(tempFile, contentType, tempFile.getName());
            HttpEntity entity = MultipartEntityBuilder.create()
                    .addPart("media", fileBody)
                    .build();

            // 4. 配置请求并执行
            HttpPost request = new HttpPost(CHECK_IMG_URL + getValidToken());
            request.setEntity(entity);

            try (CloseableHttpResponse response = httpclient.execute(request)) {
                String result = EntityUtils.toString(response.getEntity());
                JSONObject jsonResult = JSONObject.parseObject(result);
                System.out.println("检测结果: " + jsonResult);
            }
        } catch (IOException e) {
            throw new RuntimeException("内容检测失败: " + e.getMessage(), e); // 明确异常原因[8](@ref)
        }
    }
}